var https = require('https');
const { ipcMain } = require('electron');
var qs = require('querystring');

var token;
const param = qs.stringify({
    'grant_type': 'client_credentials',
    'client_id': 'Nj6U7jA0b7h5hkYoPeinDGuI',
    'client_secret': 'S6lwf9YC2TG4VKbDow40e1AmfjsCVXRm'
});

//token有限期30天,演示不做定时任务
https.get({
        hostname: 'aip.baidubce.com',
        path: '/oauth/2.0/token?' + param,
        agent: false
    }, function (res) {
        res.on("data",function(data){
            token=JSON.parse(data).access_token;
        });
    }
);

//人脸比对
ipcMain.on('witness', (event, arg) => {
    //arg.idPhoto
    //arg.scenePhoto
    var parameter=[
        {
            "image": arg.idPhoto,
            "image_type": "BASE64",
            "face_type": "IDCARD",
            "quality_control": "NORMAL",
            "liveness_control": "NONE"
        },
        {
            "image": arg.scenePhoto,
            "image_type": "BASE64",
            "face_type": "LIVE",
            "quality_control": "NORMAL",
            "liveness_control": "NONE"
        }
    ];
    parameter = JSON.stringify(parameter);
    var opt = {
         method: "POST",
         host: 'aip.baidubce.com',
         path: "/rest/2.0/face/v3/match?access_token="+token,
         headers:{
             "Content-Type": "application/json", // for json data
             "Content-Length": Buffer.byteLength(parameter)
         }
     };
    var req = https.request(opt, function(res){
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            event.sender.send('witnessResult',JSON.parse(chunk));
        });
    });
    req.write(parameter + "\n"); //发送请求
    req.end(); //请求发送完毕



})

